package com.jsmtr.rms.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jsmtr.rms.entity.*;
import com.jsmtr.rms.service.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.jsmtr.rms.utils.EnumTools;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
@RequestMapping("/Do/ZZResume")
public class DoZZResumeController {

    @Resource
    private IUtilService utilService;

    @Resource
    private IRecommendService recommendService;

    @Resource
    private ISchoolService schoolService;

    @Resource
    private IDoZZService doZZService;

    @Resource
    private IProjectService projectService;

    //[start] 查询毕业生信息

    //首页
    @RequestMapping("/")
    public String Index(HttpServletRequest request, Model model) {
        try {
            model.addAttribute("path", request.getContextPath());
            String pid = request.getParameter("pid").trim();
            String fid = request.getParameter("fid").trim();
            String deptcode = request.getParameter("deptcode").trim();

            model.addAttribute("pid", pid);
            model.addAttribute("fid", fid);
            model.addAttribute("deptcode", deptcode);
            model.addAttribute("fpath", utilService.getConfig("path"));
            StringBuilder str = new StringBuilder();
            List<HRSchoolUsers> schools = schoolService.getSchools();
            for (HRSchoolUsers school : schools) {
                str.append("<option value='" + school.getId() + "'>" + school.getUname() + "</option>");
            }
            model.addAttribute("school", str);
            //招聘岗位
            List<ProjectInfoJobs> projectJobs=utilService.getProjectJobs(pid);
            model.addAttribute("jobs",projectJobs);
            ProjectInfoFlow projectInfoFlow= projectService.getFolwById(fid);
            if(projectInfoFlow!=null){
                model.addAttribute("nowflow",projectInfoFlow.getNickname());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "Do/ZZCampus/Resume/index";
    }

    @SuppressWarnings("unchecked")
    @RequestMapping("/getusers")
    public void getusers(HttpServletRequest request, HttpServletResponse response, HRZZUser user) {
        try {
            int perpage = Integer.parseInt(request.getParameter("perpage"));
            int page = Integer.parseInt(request.getParameter("page"));
            String flowid = request.getParameter("flowid").trim();
            user.setPath("/" + flowid + "/");
            Map<String, Object> _map = new HashMap<String, Object>();
            _map.put("agefrom", request.getParameter("agefrom").trim());
            _map.put("ageto", request.getParameter("ageto").trim());
            _map.put("heightfrom", request.getParameter("heightfrom").trim());
            _map.put("heightto", request.getParameter("heightto").trim());
            _map.put("rcount",request.getParameter("rcount").trim());
            _map.put("ischangejob",request.getParameter("ischangejob"));
            Map<String, Object> map = recommendService.getUsers(page, perpage, user,_map);
            StringBuilder result = new StringBuilder();
            double pageCount = (Double) map.get("pageCount");
            double allcount = (Double) map.get("count");

            if (pageCount != 0) {
                Object object = map.get("list");
                int num = 0;
                for (HRZZUser _user : (List<HRZZUser>) object) {
                    result.append("<tr><td><input type=\"checkbox\" name='uid' value='" + _user.getId() + "' id='cb_" + _user.getId() + "' /></td>");
                    result.append("<td>" + (perpage * (page - 1) + num + 1) + "</td>");
                    result.append("<td class='link'><a target='_blank' href='"
                            + request.getContextPath() + "/UserResume/ViewDResume?id="
                            + _user.getId() + "'>" + _user.getName()
                            + "</a></td>");//简历ID和HRZZUser的ID相同
                    result.append("<td>" + _user.getGender() + "</td>");
                    result.append("<td>" + _user.getCode() + "</td>");
                    result.append("<td>" + _user.getMajor() + "</td>");
                    result.append("<td>" + _user.getGraduationtime() + "</td>");
                    result.append("<td>" + _user.getBx() + "</td>");
                    result.append("<td>" + _user.getGuake() + "</td>");
                    result.append("<td>" + _user.getTc() + "</td>");
                    result.append("<td>" + _user.getDeptname() + "</td>");
                    result.append("<td>" + _user.getRstate() + "</td>");
                    if(_user.getRstate().equalsIgnoreCase("未通过")){
                        result.append("<td>" + _user.getRrstate() + "</td>");
                    }else{
                        result.append("<td>" + _user.getRrstate() + "</td>");
                    }

                    if (_user.getOp3().equals("未公布")) {
                        result.append("<td class='true'><span>" + _user.getOp3() + "</span></td>");
                    } else {
                        result.append("<td class='false'><span>" + _user.getOp3() + "</span></td>");
                    }
                    if (_user.getFqstate().equals("已放弃")
                            && _user.getFqfid().equals(flowid)) {
                        result.append("<td class='yfq'><span>已放弃</span></td></tr>");
                    } else {
                        boolean bl = _user.getFid().equals(flowid);
                        result.append("<td class='" + bl + "'><span>" + (bl == true ? "未完成" : "已完成") + "</span></td></tr>");
                    }

                    num++;
                }
            } else {
                result.append("<tr style='display:none'><td></td></tr>");
            }
            result.append("<input type='hidden' id='pageCount' value='" + pageCount + "' />");
            result.append("<input type='hidden' id='allCount' value='" + allcount + "' />");
            utilService.printTextResult(result.toString(), response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printTextResult("<tr><td colspan='13'>读取数据失败</td></tr><input type='hidden' id='pageCount' value='0' /><input type='hidden' id='allCount' value='0' />", response);
        }

    }
    //[end]
    @ResponseBody
    @RequestMapping(value = "/getZZResumeListLayuiJson", method = RequestMethod.GET)
    public LayuiDataTableResultBean getZZResumeListLayuiJson(HttpServletRequest request, HttpServletResponse response, HRZZUser user) {
        try {
            int page = Integer.parseInt(request.getParameter("page"));
            int limit = Integer.parseInt(request.getParameter("limit"));
            String flowid = request.getParameter("flowid").trim();
            user.setPath("/" + flowid + "/");
            Map<String, Object> _map = new HashMap<String, Object>();
            _map.put("agefrom", request.getParameter("agefrom").trim());
            _map.put("ageto", request.getParameter("ageto").trim());
            _map.put("heightfrom", request.getParameter("heightfrom").trim());
            _map.put("heightto", request.getParameter("heightto").trim());
            _map.put("rcount",request.getParameter("rcount").trim());
            _map.put("ischangejob",request.getParameter("ischangejob"));
            //Map<String, Object> map = recommendService.getUsers(page, limit, user,_map);
            Map<String, Object> map = recommendService.getUserMap(page, limit, user,_map);

            double pageCount = (Double) map.get("pageCount");
            double allcount = (Double) map.get("count");

            JSONArray jsonArray = new JSONArray();
            int num = 1;
            if (pageCount != 0) {
                List<HashMap> object = (List<HashMap>)map.get("list");
                for (HashMap<String,Object> _user :  object) {
                    JSONObject jsonObject = new JSONObject();

                    jsonObject.put("id_cb","cb_" + _user.get("ID"));
                    jsonObject.put("id",limit * (page - 1) + num);
                    jsonObject.put("ContextPath",request.getContextPath()+"/UserResume/ViewDResume?id=" + _user.get("ID"));
                    jsonObject.put("NAME", _user.get("NAME"));
                    jsonObject.put("CARDNO", _user.get("CODE"));
                    jsonObject.put("SEXNAME", _user.get("GENDER"));
                    jsonObject.put("MAJORNAME", _user.get("MAJOR"));
                    jsonObject.put("GRADUATIONTIME", (_user.get("GRADUATIONTIME") == null ? "" : _user.get("GRADUATIONTIME")));
                    jsonObject.put("BX",  _user.get("BX"));
                    jsonObject.put("GUAKE", _user.get("GUAKE"));
                    jsonObject.put("HEIGHT",_user.get("HEIGHT"));
                    jsonObject.put("RSTATE", _user.get("RSTATE"));
                    jsonObject.put("RrSTATE", _user.get("RRSTATE"));
                    jsonObject.put("STATEb",_user.get("OP1"));

                    if ( _user.get("FQSTATE").toString().equals("已放弃") && _user.get("FQFID").equals(flowid)) {
                        jsonObject.put("STATEc","已放弃");
                    } else {
                        boolean bl = _user.get("FID").equals(flowid);
                        jsonObject.put("STATEc",(bl == true ? "未完成" : "已完成"));
                    }

                    jsonArray.add(jsonObject);
                    num++;
                }
            }

            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCode(0);
            result.setMsg("success");
            result.setCount((int) allcount);
            result.setData(jsonArray);

            return result;
        } catch (Exception e) {
            e.printStackTrace();

            LayuiDataTableResultBean result = new LayuiDataTableResultBean();
            result.setCount(-1);
            result.setMsg("err");
            return result;
        }
    }

    //[start] 开启关闭简历投递功能

    @RequestMapping(value = "/OpenCloseAction", method = RequestMethod.POST)
    public void OpenCloseAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            String pid = request.getParameter("pid").trim();//招聘方案ID
            String fid = request.getParameter("fid").trim();//招聘流程ID
            String deptcode = request.getParameter("deptcode").trim();//责任部门编码
            ProjectInfoFlow flow = doZZService.getCurrentFlow(pid, deptcode, fid);
            if (flow.getState() == EnumTools.PlanFlowState.已完成.ordinal()) {
                flow.setState(EnumTools.PlanFlowState.进行中.ordinal());
                utilService.editObject(flow);
                utilService.printJsonResult(true, "操作成功", "no", response);
            } else if (flow.getState() == EnumTools.PlanFlowState.进行中.ordinal()) {
                flow.setState(EnumTools.PlanFlowState.已完成.ordinal());
                utilService.editObject(flow);
                utilService.printJsonResult(true, "操作成功", "no", response);
            } else {
                utilService.printJsonResult(false, "当前不能执行此操作", "no", response);
                return;
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败", "no", response);
        }
    }

    //[end]

    //[start] 通过简历筛选
    @RequestMapping(value = "/ResumeOkAction", method = RequestMethod.POST)
    public void ResumeOkAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            String fid = request.getParameter("fid").trim();//招聘流程ID
            String deptcode = request.getParameter("deptcode").trim();//责任部门编码

            BaseUser cuser = utilService.getSessionUser(request);
            if (cuser.getUdept().equals(deptcode)) {
                //流程是否结束
                if (utilService.FlowIsDoing(fid)) {
                    String[] ids = request.getParameterValues("id");
                    if (ids != null) {
                        List<HRZZUser> editList = new ArrayList<HRZZUser>();
                        List<HRZZUser> usrs = doZZService.getUsers(ids);
                        StringBuffer errmessage=new StringBuffer();
                        if(usrs.size()==0){
                            errmessage.append("没有可执行此操作的信息！");
                        }
                        for (HRZZUser user : usrs) {
                            if(!user.getFid().equals(fid)){
                                errmessage.append(user.getName()+":流程验证错误!");
                            }else if(user.getState()!=2){
                                errmessage.append(user.getName()+":个人信息未通过!");
                            }else if(!user.getFqstate().equals("未放弃")){
                                errmessage.append(user.getName()+":已放弃本次招聘!");
                            }else{
                                user.setRrstate("已通过");
                                user.setRstate("已通过");
                                user.setRmarks(null);
                                editList.add(user);
                            }
                        }
                        if (errmessage.length()>0) {
                            utilService.printJsonResult(false, errmessage.toString(), "no", response);
                        } else {
                            utilService.editList(editList);
                            utilService.printJsonResult(true, "操作成功！", "no", response);
                        }
                    } else {
                        utilService.printJsonResult(false, "请选择应聘者！", "no", response);
                    }
                } else {
                    utilService.printJsonResult(false, "当前流程不支持此操作！", "no", response);
                }
            } else {
                utilService.printJsonResult(false, "您无权执行此操作！", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }

    //[end]

    //[start] 未通过简历筛选

    @RequestMapping("/bz")
    public String BZ(HttpServletRequest request, Model model) {
        try {
            model.addAttribute("path", request.getContextPath());
            String id = request.getParameter("id").trim();
            model.addAttribute("id", id);
            model.addAttribute("pid", request.getParameter("pid").trim());
            model.addAttribute("fid", request.getParameter("fid").trim());
            model.addAttribute("deptcode", request.getParameter("deptcode").trim());
            HRZZUser user = doZZService.getUser(id);
            model.addAttribute("bz", user.getRmarks());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "Do/ZZCampus/Resume/bz";
    }

    @RequestMapping(value = "/ResumeNoAction", method = RequestMethod.POST)
    public void ResumeNoAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            String fid = request.getParameter("fid").trim();//招聘流程ID
            String deptcode = request.getParameter("deptcode").trim();//责任部门编码

            BaseUser cuser = utilService.getSessionUser(request);
            if (cuser.getUdept().equals(deptcode)) {
                //流程是否结束
                if (utilService.FlowIsDoing(fid)) {
                    HRZZUser user = doZZService.getUser(request.getParameter("id").trim());
                    if (user.getFid().equals(fid) && user.getFqstate().equals("未放弃")) {
                        user.setRrstate("未通过");
                        user.setRstate("未通过");
                        user.setRmarks(request.getParameter("sxbz"));

                        utilService.editObject(user);
                        utilService.printJsonResult(true, "操作成功！", "no", response);
                    } else {
                        utilService.printJsonResult(false, "不能对该应聘者简历执行此操作！", "no", response);
                    }
                } else {
                    utilService.printJsonResult(false, "当前流程不支持此操作！", "no", response);
                }
            } else {
                utilService.printJsonResult(false, "您无权执行此操作！", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }

    //[end]


    //[start] 未通过简历筛选
    @RequestMapping(value = "/ResumeAllNoAction", method = RequestMethod.POST)
    public void ResumeAllNoAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            String fid = request.getParameter("fid").trim();//招聘流程ID
            String deptcode = request.getParameter("deptcode").trim();//责任部门编码
            BaseUser cuser = utilService.getSessionUser(request);

            if (cuser.getUdept().equals(deptcode)) {
                //流程是否结束
                if (utilService.FlowIsDoing(fid)) {
                    String sid=request.getParameter("ids");
                    String[] ids=sid.split(",");
                    if(ids!=null&&ids.length>0){
                        List<HRZZUser> editList = new ArrayList<HRZZUser>();
                        List<HRZZUser> users = doZZService.getUsers(ids);
                        if(users!=null&&users.size()>0){
                            for (HRZZUser user : users) {
                                user.setRrstate("未通过");
                                user.setRstate("未通过");
                                user.setRmarks(request.getParameter("sxbz"));
                            }
                            editList.addAll(users);
                        }
                        if (editList.size() > 0) {
                            utilService.editList(editList);
                            utilService.printJsonResult(true, "操作成功！", "no", response);
                        } else {
                            utilService.printJsonResult(false, "当前选中的简历不能执行此操作！", "no", response);
                        }

                    }else {
                        utilService.printJsonResult(false, "请至少选择应聘者！", "no", response);
                    }
                } else {
                    utilService.printJsonResult(false, "当前流程不支持此操作！", "no", response);
                }
            } else {
                utilService.printJsonResult(false, "您无权执行此操作！", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }
    //[end]

    //[start] 导出应聘者信息

    @RequestMapping(value = "/DownAction")
    public void DownAction(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("application/vnd.ms-excel");
        String codedFileName = null;
        OutputStream fOut = null;
        try {
            String pid = request.getParameter("pid").trim();//招聘方案ID

            codedFileName = java.net.URLEncoder.encode("应聘者信息", "UTF-8");
            response.setHeader("content-disposition", "attachment;filename=" + codedFileName + ".xls");
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet();

            //[start] 表头

            HSSFRow headrow = sheet.createRow(0);//创建一行
            HSSFCell headcel0 = headrow.createCell(0);
            headcel0.setCellValue(new HSSFRichTextString("序号"));
            HSSFCell headcel1 = headrow.createCell(1);
            headcel1.setCellValue(new HSSFRichTextString("姓名"));
            HSSFCell headcel2 = headrow.createCell(2);
            headcel2.setCellValue(new HSSFRichTextString("身份证"));
            HSSFCell headcel3 = headrow.createCell(3);
            headcel3.setCellValue(new HSSFRichTextString("现居住地"));

            //[end]

            List<Object[]> objs = doZZService.getUsers(pid);
            if (objs != null) {
                int i = 1;
                for (Object[] obj : objs) {
                    HSSFRow row = sheet.createRow(i);//创建一行

                    HSSFCell cell = row.createCell(0);//创建一列
                    cell.setCellType(CellType.STRING);
                    cell.setCellValue(new HSSFRichTextString(String.valueOf(i)));

                    for (int j = 0; j < 3; j++) {
                        HSSFCell _cell = row.createCell(j + 1);//创建一列
                        _cell.setCellType(CellType.STRING);
                        _cell.setCellValue(new HSSFRichTextString(obj[j] == null ? "" : obj[j].toString()));

                    }
                    i++;
                }
            }

            fOut = response.getOutputStream();
            workbook.write(fOut);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fOut.flush();
                fOut.close();
            } catch (IOException e) {
            }
        }
    }

    //[end]

    //[start] 流程扭转到下一步

    @SuppressWarnings({"rawtypes", "unchecked"})
    @RequestMapping(value = "/NextAction", method = RequestMethod.POST)
    public void NextAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            String[] ids = request.getParameterValues("id");//人员信息ID
            if (ids != null) {
                String pid = request.getParameter("pid").trim();//招聘方案ID
                String fid = request.getParameter("fid").trim();//招聘流程ID
                String deptcode = request.getParameter("deptcode").trim();//责任部门编码
                BaseUser usr = utilService.getSessionUser(request);
                if (usr.getUdept().equals(deptcode)) {
                    List editlist = new ArrayList();
                    List<HRZZUser> users = doZZService.getUsers(pid, deptcode, ids);
                    List<DUserResume> usrDs = doZZService.getUsersDuser(ids);
                    DUserResume usrDsTemp = new DUserResume();
                    ProjectInfoFlow nFlow = doZZService.getNextFlow(pid, deptcode, fid);
                    for (HRZZUser user : users) {
                        if (user.getFid().equals(fid)
                                && user.getState()==2
                                &&( user.getRstate().equals("已通过")||user.getRstate().equals("通过")||user.getRstate().equals("合格")||user.getRstate().equals("已合格"))
                                &&( user.getRrstate().equals("已通过")||user.getRrstate().equals("通过")||user.getRrstate().equals("合格")||user.getRrstate().equals("已合格"))
                                && user.getFqstate().equals("未放弃")) {

                            for(int i =0 ;i<usrDs.size(); i++){
                                if(usrDs.get(i).getUserid().equals(user.getId())){
                                    usrDsTemp = usrDs.get(i);
                                    break;
                                }
                            }

                            user.setFid(nFlow.getId());
                            user.setPath(user.getPath() + nFlow.getId() + "/");
                            editlist.add(user);

                            usrDsTemp.setFid(nFlow.getId());
                            usrDsTemp.setPath(user.getPath() + nFlow.getId() + "/");
                            usrDsTemp.setJname(user.getJob());
                            editlist.add(usrDsTemp);
                        }
                    }

                    if (editlist.size() > 0) {
                        nFlow.setState(EnumTools.PlanFlowState.进行中.ordinal());
                        editlist.add(nFlow);

                        utilService.editList(editlist);
                        utilService.printJsonResult(true, "操作成功！", "no", response);
                    } else {
                        utilService.printJsonResult(false, "当前选中的信息不能执行此操作！", "no", response);
                    }
                } else {
                    utilService.printJsonResult(false, "您无权执行此操作！", "no", response);
                }
            } else {
                utilService.printJsonResult(false, "请选择人员信息！", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }

    //[end]


}
